from django.shortcuts import render
from cost_query.models import CostQuery
from cost_query.serializers import CostQuerySerializers
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core import serializers
import json

# class CostQueryViews(generics.ListCreateAPIView):
#     queryset = CostQuery.objects.all()
#     serializer_class = CostQuerySerializers
import re


class CostQueryViews(APIView):
    def post(self, request, *args, **kwargs):
        id_number = request.POST.get('id_number')
        is_number = re.match(r"^[1-9]\d{5}(18|19|2([0-9]))\d{2}(0[0-9]|10|11|12)([0-2][1-9]|30|31)\d{3}[0-9Xx]$",id_number)
        if not is_number:
            data = {
                'msg': '身份证格式错误',
                'code': '400'
            }
            return Response(data)
        else:
            users = CostQuery.objects.filter(id_number=id_number)
            if users:
                user_list = json.loads(serializers.serialize('json', users))
                for i in user_list:
                    user_json = i['fields']
                    return Response(user_json)
            else:
                data = {
                    'msg': '身份证号不存在',
                    'code': 401
                }
                return Response(data)
